package com.grf.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.grf.mapper.UserMapper;
import com.grf.pojo.User;
import com.grf.service.UserService;
import com.grf.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    UserMapper userMapper;
    @Autowired
    RedisUtil redisUtil;

    @Override
    public User getUserByName(String userName) {
        User user = null;
        boolean hasKey = redisUtil.hasKey(userName);
        // 如果Redis中存在Key值
        if (true == hasKey) {
            user = JSONObject.parseObject(redisUtil.get(userName).toString(), User.class);
            System.out.println("从redis中读取");
        } else { // 否则从数据库中读取
            user = userMapper.getUserByName(userName);
            System.out.println("从mysql中读取");
            //然后存入Redis中
            Object str = JSONObject.toJSONString(user);
            redisUtil.set(user.getUserName(), str);
            System.out.println("数据存入缓存");
        }
        return user;
    }

}
